package com.github.cakin.shiro.chapter23.client;

import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import javax.servlet.Filter;

/**
 * @className: ClientShiroFilterFactoryBean
 * @description: ClientShiroFilterFactoryBean
 * @date: 2020/6/2
 * @author: cakin
 */
public class ClientShiroFilterFactoryBean extends ShiroFilterFactoryBean implements ApplicationContextAware {
    /**
     * 应用上下文
     */
    private ApplicationContext applicationContext;

    public void setApplicationContext( ApplicationContext applicationContext ) {
        this.applicationContext = applicationContext;
    }

    /**
     * 功能描述：设置 filters字符串
     *
     * @param filters 过滤器列表
     * @author cakin
     * @date 2020/6/2
     */
    public void setFiltersStr( String filters ) {
        if (StringUtils.isEmpty(filters)) {
            return;
        }
        // 过滤器 name=filter-ref;name=filter-ref
        String[] filterArray = filters.split(";");
        for (String filter : filterArray) {
            String[] o = filter.split("=");
            getFilters().put(o[0], (Filter) applicationContext.getBean(o[1]));
        }
    }

    /**
     * 功能描述：设置filterChainDefinitions，从配置文件shiro-client-default.properties中读取
     *
     * @param filterChainDefinitions 拦截器链的定义
     * @author cakin
     * @date 2020/6/2
     */
    public void setFilterChainDefinitionsStr( String filterChainDefinitions ) {
        if (StringUtils.isEmpty(filterChainDefinitions)) {
            return;
        }
        // #过滤器链 格式 url=filters;url=filters
        String[] chainDefinitionsArray = filterChainDefinitions.split(";");
        for (String filter : chainDefinitionsArray) {
            String[] o = filter.split("=");
            getFilterChainDefinitionMap().put(o[0], o[1]);
        }
    }
}
